package com.chen.web;

import com.alibaba.fastjson.JSON;
import com.chen.dao.AddressDao;
import com.chen.dao.CategoryDao;
import com.chen.dao.GoodsDao;
import com.chen.dao.ShopcarDao;
import com.chen.dao.impl.AddressDaoImpl;
import com.chen.dao.impl.CategoryDaoImp;
import com.chen.dao.impl.GoodsDaoImpl;
import com.chen.dao.impl.ShopcarDaoImpl;
import com.chen.entity.*;
import com.chen.util.BaseServlet;
import com.chen.util.UUIDUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.transform.Result;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/category/*")
public class CategoryServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String baseURL = request.getContextPath(); //获取项目基准路径
        String uri = request.getRequestURI();//截取项目二级路径
        String path = uri.substring(uri.lastIndexOf("/") + 1);
        JSONBean jsonBean = new JSONBean();
        GoodsDao goodsDao = new GoodsDaoImpl();
        CategoryDao categoryDao = new CategoryDaoImp();
        ShopcarDao shopcarDao = new ShopcarDaoImpl();
        if ("category_list.do".equals(path)) {
            List<Category> categorylist = categoryDao.findAll();
            request.setAttribute("categorylist", categorylist);
            request.getRequestDispatcher(baseURL + "/phone/category.jsp").forward(request, response);
        } else if ("goods_list.do".equals(path)) {
            find(request, response, goodsDao);
        } else if ("goods_detail.do".equals(path)) {
            String id = request.getParameter("id");
            Goods goods = goodsDao.findById(id);
            request.setAttribute("goods", goods);
            request.getRequestDispatcher(baseURL + "/phone/detail.jsp").forward(request, response);
        } else if ("goods_car.do".equals(path)) {
            addCar(request, response, jsonBean, goodsDao, shopcarDao);
            return;
        } else if ("goods_carList.do".equals(path)) {
            HttpSession session = request.getSession();
            String user_id = (String) session.getAttribute("user_id");
            List<Shopcart> shopcartList = shopcarDao.findByUserId(user_id);
            request.setAttribute("shopcartList", shopcartList);
            request.getRequestDispatcher(baseURL + "/phone/shopcart.jsp").forward(request, response);
        } else if ("goods_carUpdate.do".equals(path)) {
            UpdateCar(request, response, jsonBean, shopcarDao);
        } else if ("deleteCar.do".equals(path)) {
            deleteCar(request, response, jsonBean, shopcarDao);
        } else if ("submitCar.do".equals(path)) {
            submitCar(request, response, baseURL, shopcarDao);
            return;
        }else if("submitorder.do".equals(path)){
            String ids1 = request.getParameter("ids");
            System.out.println("ids1 = " + ids1);
            String[] ids = ids1.replaceAll("\"", "").split(",");
            List<Shopcart> shopcartList = new ArrayList<>();
            for (String id : ids) {
                System.out.println("id = " + id);
            }
            for (int i = 0; i < ids.length; i++) {
                Shopcart shopcart = shopcarDao.findById(ids[i]);
                System.out.println("shopcart = " + shopcart);
                shopcartList.add(shopcart);
            }
            HttpSession session = request.getSession();
            String user_id = (String) session.getAttribute("user_id");
            AddressDao addressDao = new AddressDaoImpl();
            List<Address> addressList = addressDao.findPage(1, 1);
            request.setAttribute("addressList",addressList);
            request.setAttribute("shopcartList",shopcartList);
            request.getRequestDispatcher(baseURL+"/phone/order.jsp").forward(request,response);
        }else if("batchDelete.do".equals(path)){
            String ids1 = request.getParameter("ids");
            System.out.println("ids1 = " + ids1);
            String[] ids = ids1.replaceAll("\"", "").split(",");
            for (String id : ids) {
                System.out.println("id = " + id);
                shopcarDao.delete(id);
            }
            request.setAttribute("result",1);
            request.getRequestDispatcher(baseURL+"/category/goods_carList.do").forward(request,response);
        }
    }

    private void deleteCar(HttpServletRequest request, HttpServletResponse response, JSONBean jsonBean, ShopcarDao shopcarDao) throws IOException {
        String id = request.getParameter("id");
        int result = shopcarDao.delete(id);
        if (result > 0) {
            jsonBean.setSuccess("删除成功");
        } else {
            jsonBean.setFail("删除失败");
        }
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter(); //获取输出
        String json = JSON.toJSONString(jsonBean);
        out.print(json);
        out.close();
    }

    private void submitCar(HttpServletRequest request, HttpServletResponse response, String baseURL, ShopcarDao shopcarDao) throws ServletException, IOException {
        String ids1 = request.getParameter("ids");
        String[] ids = ids1.replaceAll("\"", "").split(",");
        List<Shopcart> shopcartList = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            Shopcart shopcart = shopcarDao.findById(ids[i]);
            shopcartList.add(shopcart);
        }
        request.setAttribute("shopcartList",shopcartList);
        request.getRequestDispatcher(baseURL+"/phone/tureorder.jsp").forward(request,response);
    }

    private void UpdateCar(HttpServletRequest request, HttpServletResponse response, JSONBean jsonBean, ShopcarDao shopcarDao) throws IOException {
        String carid = request.getParameter("id");
        String num = request.getParameter("num");
        Integer IntNum = Integer.parseInt(num);
        Shopcart shopcart = shopcarDao.findById(carid);
        shopcart.setGoods_num(IntNum);
        int result = shopcarDao.update(shopcart);
        if (result > 0) {
            jsonBean.setSuccess("修改成功");
        } else {
            jsonBean.setFail("修改失败");
        }
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter(); //获取输出
        String json = JSON.toJSONString(jsonBean);
        out.print(json);
        out.close();
    }

    private void addCar(HttpServletRequest request, HttpServletResponse response, JSONBean jsonBean, GoodsDao goodsDao, ShopcarDao shopcarDao) throws IOException {
        String id = request.getParameter("id");//获取到商品id
        String num = request.getParameter("num");//获取到商品数量
        Goods goods = goodsDao.findById(id);
        int numInt = Integer.parseInt(num);
        HttpSession session = request.getSession();
        String user_id = (String) session.getAttribute("user_id");
        Shopcart shopcart = shopcarDao.findGoodsUserId(user_id, id);//根据商品id和用户id查找出唯一的购物车对象
        if (shopcart != null) {//如果不为空则代表该用户购物车内已有该商品，则修改num的值
            int numInt1 = numInt + shopcart.getGoods_num();
            System.out.println("shopcart = " + shopcart);
            shopcart.setGoods_num(numInt1);
            int result = shopcarDao.update(shopcart);
            if (result > 0) {
                jsonBean.setSuccess("加入购物车成功");
            } else {
                jsonBean.setFail("加入购物车失败");
            }
        } else {
            Shopcart shopcart1 = new Shopcart();
            String uuid = UUIDUtils.getUUID();
            shopcart1.setShopcart_id(uuid);
            shopcart1.setGoods_id(id);
            shopcart1.setGoods_name(goods.getGoods_name());
            shopcart1.setGoods_price(goods.getGoods_price());
            shopcart1.setGoods_img(goods.getGoods_img());
            shopcart1.setGoods_num(numInt);
            shopcart1.setUser_id(user_id);
            int result = shopcarDao.save(shopcart1);
            if (result > 0) {
                jsonBean.setSuccess("加入购物车成功");
            } else {
                jsonBean.setFail("加入购物车失败");
            }
        }
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter(); //获取输出
        String json = JSON.toJSONString(jsonBean);
        out.print(json);
        out.close();
    }

    private void find(HttpServletRequest request, HttpServletResponse response, GoodsDao goodsDao) throws IOException {
        String category = request.getParameter("category");
        Map<String, Object> map = new HashMap<>();
        List<Goods> goodsList = goodsDao.findByName(category);
        map.put("goodsList", goodsList);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter(); //获取输出
        String json = JSON.toJSONString(map);
        out.print(json);
        out.close();
    }
}
